package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mainService.HTTPService;
import mainService.ServiceParams;
import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;

/**
 * Servizio di Registrazione
 * 
 * @author Daniel Procop, Mattia Grecchi
 */
public class RegistrazioneService implements HTTPService {

	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {


		String username = params.getValue("username");

		String password = params.getValue("password");
		String nomeprogetto = params.getValue("nomeprogetto");
		String descrizione = params.getValue("descprogetto");

	
		IConnection manager = new ConnectionManager();
		manager.connect();

		Connection conn = manager.getConnection();

		try {
			Statement stmt = conn.createStatement();

			String qry = "SELECT username from users where username='"
					+ username + "'";

			ResultSet rs = stmt.executeQuery(qry);

			if (rs.first()) {
				return getPagina(params, "usernamePresente.html");
			}

			String cmd = "INSERT INTO projects (name,description) VALUES ('"
					+ nomeprogetto + "', '" + descrizione + "')";
			if (stmt.executeUpdate(cmd) == 0) {
				return getPagina(params, "inserimentoNonCorretto.html");
			}

			qry = "SELECT id_project from projects where name='" + nomeprogetto
					+ "' and description='" + descrizione + "'";
			rs = stmt.executeQuery(qry);

			rs.next();
			int id_pr = rs.getInt("id_project");

			cmd = "INSERT INTO users (username, password, role, id_project) VALUES ('"
					+ username
					+ "', '"
					+ password
					+ "', 'Project Manager', '"
					+ id_pr + "')";
			if (stmt.executeUpdate(cmd) == 0) {
				return getPagina(params, "inserimentoNonCorretto.html");
			} else {
				return getPagina(params, "registrazioneRiuscita.html");
			}

		} catch (SQLException e) {
			e.printStackTrace();
			return getPagina(params, "inserimentoNonCorretto.html");
		}
	}

	// restituisce pagina
	private ArrayList<String> getPagina(ServiceParams params, String pagina) {
		params.addParam("file", pagina);
		return (new HttpFileServer()).getServiceResult(params);
	}
}
